<template>
  <div class="app-container">
    <el-form inline>
      <!-- 表单元素 -->
      <el-form-item>
        <el-input
          v-model="searchContent"
          placeholder="请输入内容"
          @change="resetForm"
        />
      </el-form-item>
      <!-- 查询与情况的按钮 -->
      <el-button type="primary" icon="el-icon-search" @click="search"
        >查询</el-button
      >
      <el-button
        type="default"
        @click="resetSearch"
        v-show="searchContent !== ''"
        >清空</el-button
      >
    </el-form>

    <!-- table表格：展示用户信息的地方 -->
    <el-table border stripe v-loading="listLoading" :data="users">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="avatar" label="头像" width="150">
        <template slot-scope="{ row, $index }">
          <img
            :src="row.avatar || require('@/assets/image/mrtx.png')"
            alt="用户头像"
            style="width: 80px; height: 80px; border-radius: 50% 50%"
          />
        </template>
      </el-table-column>
      <el-table-column prop="user_name" label="用户名" width="200" />
      <el-table-column prop="sex" label="性别" width="100">
        <template slot-scope="{ row }">
          {{ row.sex == "0" ? "男" : row.sex == "1" ? "女" : "未知" }}
        </template>
      </el-table-column>
      <el-table-column prop="phone_number" label="手机号码" width="200" />
      <el-table-column prop="user_type" label="用户类型" width="150">
        <template slot-scope="{ row }">
          {{
            row.user_type == "0"
              ? "管理员"
              : row.user_type == "1"
              ? "普通用户"
              : "教练"
          }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="账号状态" width="150">
        <template slot-scope="{ row }">
          {{ row.status == "0" ? "正常" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间">
        <template slot-scope="{ row }">
          <div v-if="row.create_time">
            {{ row.create_time.replace("T", " ") }}
          </div>
          <div v-else>无</div>
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间">
        <template slot-scope="{ row }">
          <div v-if="row.update_time">
            {{ row.update_time.replace("T", " ") }}
          </div>
          <div v-else>无</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template slot-scope="{ row }">
          <HintButton
            :type="row.status == '0' ? 'success' : 'info'"
            size="mini"
            icon="el-icon-user-solid"
            title="修改状态"
            @click="showUpdateStatus(row.status, row.id)"
          />
          <el-popconfirm
            :title="`确定修改用户 ${row.user_name} 的用户类型吗?`"
            @confirm="ChangeIdentity(row)"
          >
            <HintButton
              style="margin-left: 10px"
              slot="reference"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              title="修改权限"
            />
          </el-popconfirm>
          <el-popconfirm
            :title="`确定删除用户 ${row.user_name} 吗?`"
            @confirm="removeUser(row.id)"
          >
            <HintButton
              style="margin-left: 10px"
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="删除用户"
            />
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="current"
      :total="total"
      :page-size="count"
      :page-sizes="[4, 10, 20, 30, 40, 50]"
      style="padding: 20px 0"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getUsers"
      @size-change="handleSizeChange"
    />
    <!-- 对话框的结构 -->
    <!-- <el-dialog title="添加用户" :visible.sync="dialogUserVisible">
      <el-form
        ref="userForm"
        :model="user"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="user.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="user.sex" placeholder="请选择">
            <el-option label="男" value="0"> </el-option>
            <el-option label="女" value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input type="text" v-model="user.phoneNumber" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="user.userType" placeholder="请选择">
            <el-option label="管理员" value="0"> </el-option>
            <el-option label="普通用户" value="1"> </el-option>
            <el-option label="微信用户" value="2"> </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="addUser"
          >确 定</el-button
        >
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
// import { getToken } from "@/utils/auth";
export default {
  name: "Users",
  data() {
    return {
      listLoading: false, // 是否显示列表加载的提示
      searchContent: "",
      
      searchFormFlag: false,
      users: [], // 用户列表当前页的用户列表
      current: 1, // 当前页码
      count: 4, // 每页数量
      total: 0, // 总数量
      user: {
        userName: "",
        password: "",
        sex: "",
        phoneNumber: "",
        userType: "",
      }, // 当前要操作的user
      dialogUserVisible: false, // 是否显示用户添加/修改的dialog
      // userRules: {
      //   // 用户添加/修改表单的校验规则
      //   userName: [{ validator: checkNull, trigger: "blur" }],
      //   phoneNumber: [{ validator: checkPhone, trigger: "blur" }],
      //   password: [{ validator: validatePassword, trigger: "blur" }],
      //   sex: [{ validator: checkNull, trigger: "blur" }],
      //   userType: [{ validator: checkNull, trigger: "blur" }],
      // },
      loading: false, // 是否正在提交请求中

    };
  },

  //发请求一般情况下，我们都是在mounted去发，但是也可以在created内部去发
  created() {
    this.getUsers();
  },

  methods: {
    // 获取分页列表
    async getUsers(pages = 1) {
      if (this.searchFormFlag) {
        await this.search(pages);
        return;
      }
      this.current = pages;
      const { current, count } = this;
      this.listLoading = true;
      const result = await this.$API.userList
        .reqGetUsers({ current, count })
        .then((result) => {
          console.log(result, "getUsers");
          if (result.resultCode == 200) {
            this.total = result.data.total;
            this.users = result.data.records;
          } else {
            this.$message.error(result.msg);
          }
        })
        .catch(() => {
          this.$message.error("获取列表失败");
        });
      this.listLoading = false;
    },
    // 处理pageSize发生改变的监听回调
    handleSizeChange(pageSize) {
      this.count = pageSize;
      this.getUsers();
    },
    //   根据输入进行搜索
    async search(pages) {
      if (this.searchContent.trim() == "") {
        this.searchContent = "";
        return;
      }
      console.log(typeof pages);
      if (typeof pages == "number") {
        console.log(pages);
        this.current = pages;
      } else {
        this.current = 1;
      }
      this.searchFormFlag = true;
      const { current, count } = this;
      this.listLoading = true;
      const condition = this.searchContent;
      const result = await this.$API.userList
        .reqSearchUser({ current, count, condition })
        .then((result) => {
          this.users = result.data.records;
          this.total = result.data.total;
        })
        .catch(() => {
          this.$message.error("获取列表失败");
        });
      this.listLoading = false;
    },
    // 清空搜索框内容清空
    resetForm() {
      if (this.searchContent == "") {
        if (this.searchFormFlag == true) {
          this.searchFormFlag = false;
          this.getUsers();
        }
      }
    },
    // 清空按钮清空
    resetSearch() {
      if (this.searchFormFlag == true) {
        this.searchContent = "";
        this.searchFormFlag = false;
        this.getUsers();
      } else {
        this.searchContent = "";
      }
    },
    // 修改状态
    async showUpdateStatus(status, id) {
      if (status == "0") {
        const result = await this.$API.userList.reqChangeStatus({
          status: "1",
          id,
        });
        if (result.resultCode == 200) {
          this.$message.success("修改成功!");
          this.getUsers(this.current);
        } else {
          this.$message.error("修改失败");
        }
      } else {
        const result = await this.$API.userList.reqChangeStatus({
          status: "0",
          id,
        });
        if (result.resultCode == 200) {
          this.$message.success("修改成功!");
          this.getUsers(this.current);
        } else {
          this.$message.error("修改失败");
        }
      }
    },
    async ChangeIdentity(row) {
      let params = { userId: row.id };
      console.log(row.user_type);
      if (row.user_type == "1") {
        params.type = "2";
      } else if (row.user_type == "2") {
        params.type = "1";
      }
      const result = await this.$API.userList.reqChangeIdentity(params);
      console.log(result, "ChangeIdentity");
      if (result.resultCode == 200) {
        this.$message.success("修改成功!");
        this.getUsers(this.current);
      } else {
        this.$message.error("修改失败");
      }
    },
    phoneInfoCancel() {
      this.phoneForm = {
        phone_number: "",
        nwePhone: "",
      };
      this.showPhoneInfo = false;
    },
    async phoneInfoDefine() {
      this.$refs.phoneForm.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          this.$API.userList
            .reqChangePhone({
              id: this.phoneForm.id,
              phoneNumber: this.phoneForm.nwePhone,
            })
            .then((res) => {
              if (res.resultCode == 200) {
                this.loading = false;
                this.$message.success("修改成功!");
                this.getUsers(this.current);
                this.phoneForm = {
                  phone_number: "",
                  nwePhone: "",
                };
                this.showPhoneInfo = false;
              } else {
                this.loading = false;
                this.$message.error("修改失败");
              }
            })
            .catch(() => {
              this.loading = false;
              this.$message.error("修改失败");
            });
        } else {
          return;
        }
      });
    },
    // 删除当前用户
    async removeUser(id) {
      const result = await this.$API.userList.reqdeleteUser({ userId: id });
      if (result.resultCode == 200) {
        this.$message.success("删除成功!");
        this.getUsers(
          this.users.length === 1 ? this.current - 1 : this.current
        );
      } else {
        this.$message.error("删除失败");
      }
      console.log(result);
    },
    /*
        显示添加用户的界面
        */
    // showAddUser() {
    //   this.user = {
    //     userName: "",
    //     password: "",
    //     sex: "",
    //     phoneNumber: "",
    //     userType: "",
    //   };
    //   this.dialogUserVisible = true;
    //   this.$nextTick(() => this.$refs.userForm.clearValidate());
    // },
    /*
        取消用户的保存或更新
        */
    // cancel() {
    //   this.dialogUserVisible = false;
    //   this.user = {
    //     userName: "123",
    //     password: "123456",
    //     sex: "",
    //     phoneNumber: "",
    //     userType: "",
    //   };
    // },
    // 添加用户
    // addUser() {
    //   this.$refs.userForm.validate(async (valid) => {
    //     if (valid) {
    //       const user = this.user;
    //       this.loading = true;
    //       const result = await this.$API.userList.reqAddUsers(user);
    //       console.log(result);
    //       if (result.resultCode == 200) {
    //         this.loading = false;
    //         this.$message.success("添加成功!");
    //         // this.getUsers(user.id ? this.page : 1)
    //         this.getUsers(this.current);
    //         this.user = {};
    //         this.dialogUserVisible = false;
    //       } else {
    //         this.loading = false;
    //         this.$message.error("添加失败");
    //       }
    //     } else {
    //       return;
    //     }
    //   });
    // },
  },
  computed: {
    // userName() {
    //   return this.$store.state.userInfo.userName || getToken("userName");
    // },
  },
};
</script>

<style lang="scss" scoped>
// .el-select {
//     /deep/.el-input {
//         width: 150%;
//     }
// }
/deep/.Import {
  .item {
    margin-bottom: 5px;
    height: 44px;
    display: flex;
    align-items: center;

    .ImportSpan {
      font-size: 16px;
    }

    .uploadBtn {
      display: inline-block;
      width: 88px;
      height: 40px;
    }
  }

  // .download{

  // }
}

/deep/.el-upload-dragger {
  display: inline-block;
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 4px;
}
</style>
